<template>
  <!-- 客户信息 -->
  <div class="addCsmDialog">
    <el-form v-show="activeTabName === 'customer'" ref="dataForm" class="form" :rules="rules" :model="formTemp" label-position="right" label-width="110px">
      <el-collapse v-model="activeNames" class="collapse">
        <el-collapse-item title="基本信息" name="1">
          <el-row :gutter="16" class="row-box">
            <el-col :span="8">
              <el-form-item label="客户类型:" prop="csmType">
                <el-select v-model="formTemp.csmType" placeholder="请选择" @change="changeCsmType">
                  <el-option
                    v-for="item in csmTypeMap"
                    :key="item.value"
                    :label="item.desc"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="户号:" prop="csmCode">
                <el-input v-model.trim="formTemp.csmCode" :maxlength="20" placeholder="" clearable disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称:" prop="csmName">
                <el-input v-model.trim="formTemp.csmName" :maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用气性质" prop="csmType">
                <el-select v-model="formTemp.subType" placeholder="请选择">
                  <el-option
                    v-for="item in subTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item title="实名认证信息" name="2">
          <el-row :gutter="16" class="row-box">
            <el-col :span="8">
              <el-form-item label="身份证姓名:" prop="sfzName">
                <el-input v-model.trim="formTemp.sfzName" :maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证号:" prop="sfzh">
                <el-input v-model.trim="formTemp.sfzh" :maxlength="18" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证地址:" prop="sfzAddress">
                <el-input v-model.trim="formTemp.sfzAddress" :maxlength="150" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item v-if="formTemp.csmType === 2" title="营业执照信息" name="3">
          <el-row :gutter="16" class="row-box">
            <el-col :span="8">
              <el-form-item label="证件号码:" prop="zzbh">
                <el-input v-model.trim="formTemp.zzbh" :maxlength="20" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row :gutter="16" class="row-box">
            <el-col :span="24">
              <el-form-item label="证件图片:">
                <el-upload
                  action="#"
                  list-type="picture-card"
                  :file-list="fileList"
                  :auto-upload="false"
                  multiple
                  :on-change="uploadChange"
                >
                  <i slot="default" class="el-icon-plus" />
                  <div slot="file" slot-scope="{file}">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                        <i class="el-icon-zoom-in" />
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                      >
                        <i class="el-icon-delete" />
                      </span>
                    </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" append-to-body>
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-collapse-item>
        <el-collapse-item title="配送地址信息" name="4">
          <el-button v-if="formTemp.addressItems.length===0" type="primary" class="addCardBtn" @click="addCsminfo">新增</el-button>
          <div style="width: 100%;">
            <div v-for="(item, index) in formTemp.addressItems" :key="index" class="csminfoBox">
              <el-row :gutter="16">
                <el-col :span="8">
                  <el-form-item label="联系人名称:" :prop="'addressItems.'+index+'.contact'" :rules="rules.contact">
                    <el-input v-model.trim="item.contact" :maxlength="20" @change="contactChange" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="联系人电话:" :prop="'addressItems.'+index+'.csmPhone'" :rules="rules.csmPhone">
                    <el-input v-model.trim="item.csmPhone" :maxlength="20" @change="(value)=>crmPhoneChange(value, item.rowId, index)" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="省市区:" :props="'addressItems.'+index+'.addressProps'" :rules="rules.addressProps">
                    <el-cascader v-if="item.area&&item.area.length === 4" :ref="'cascader'+index" v-model="item.area" :props="addressProps" clearable style="width: 100%;" @visible-change="visibleChange" />
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="详细地址:" :prop="'addressItems.'+index+'.csmAddress'" :rules="rules.csmAddress">
                    <div style="display: flex;">
                      <el-input v-model.trim="item.csmAddress" :maxlength="50" style="width: 85%;" />
                      <el-button type="primary" style="width: 15%;" @click="location(index)">定位</el-button>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="门牌号:" :prop="'addressItems.'+index+'.doorplate'" :rules="rules.doorplate">
                    <el-input v-model.trim="item.doorplate" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="楼层:" :prop="'addressItems.'+index+'.csmFloor'" :rules="rules.csmFloor">
                    <el-input v-model.trim="item.csmFloor" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="所属机构:" :prop="'addressItems.'+index+'.orgSNNo'" :rules="rules.orgSNNo">
                    <el-tree-select
                      v-model="item.orgSNNo"
                      :clearable="false"
                      class="tree-select"
                      :popover-width="360"
                      :select-params="{
                        clearable: true,
                        placeholder: '请选择',
                      }"
                      :tree-params=" {
                        'expand-on-click-node': false,
                        'highlight-current': true,
                        'filterable': true,
                        props:{
                          value:'orgSNNo',
                          label: 'orgName',
                          disabled: 'disabled',
                        },
                        data: treeData
                      }"
                      @node-click="(value)=> selectTreeChange(value, index)"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <div class="bottomBtn">
                    <div v-if="index===formTemp.addressItems.length-1" class="btn" @click="addCsminfo">新增</div>
                    <div v-if="formTemp.addressItems.length>1" class="btn danger" @click="removeCsminfo(index)">移除</div>
                    <div class="btn">
                      <span>默认地址</span>
                      <el-switch v-model="item.isMain" @change="(value)=>isMainChange(value,item.csmPhone,index)" />
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-collapse-item>
        <el-collapse-item title="话务联系人信息" name="5">
          <el-button v-if="formTemp.phoneItems.length===0" type="primary" class="addCardBtn" @click="addLinkMan">新增</el-button>
          <div v-for="(item, index) in formTemp.phoneItems" :key="index" class="csminfoBox">
            <el-row :gutter="16">
              <el-col :span="8">
                <el-form-item label="联系人名称:" :prop="'phoneItems.'+index+'.contact'" :rules="rules.contact">
                  <el-input v-model.trim="item.contact" :disabled="item.disabled" :maxlength="20" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话:" :prop="'phoneItems.'+index+'.csmPhone'" :rules="rules.csmPhone">
                  <el-input v-model.trim="item.csmPhone" :disabled="item.disabled" :maxlength="20" @change="(value)=>phoneChange(value,index)" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-button v-show="formTemp.phoneItems.length>1" type="danger" @click="removeLinkMan(index)">
                  删除
                </el-button>
                <el-button v-show="index===formTemp.phoneItems.length-1" type="primary" @click="addLinkMan">
                  添加
                </el-button>
              </el-col>
            </el-row>
          </div>
        </el-collapse-item>
        <el-collapse-item title="开户信息(点击展开更多可填项)" name="6">
          <el-row :gutter="16" class="row-box">
            <el-col :span="8">
              <el-form-item label="开户类型:" prop="newType">
                <el-select v-model="formTemp.newType" placeholder="请选择">
                  <el-option
                    v-for="item in newTypeMap"
                    :key="item.value"
                    :label="item.desc"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户来源:" prop="newFrom">
                <el-select v-model="formTemp.newFrom" placeholder="请选择">
                  <el-option
                    v-for="item in customerFromPlatMap"
                    :key="item.value"
                    :label="item.desc"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售人员:" prop="salesmanName">
                <el-input v-model="formTemp.salesmanName" readonly>
                  <el-button v-if="!formTemp.salesmanName" slot="append" class="append-search" @click="openSalesman">获取</el-button>
                  <el-button v-else slot="append" class="append-search" @click.prevent="clearSalesman">清除</el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户日期:" prop="createTime">
                <el-date-picker
                  v-model="formTemp.createTime"
                  style="width: 100%;"
                  :clearable="false"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否自提:" prop="isPickUp">
                <el-select v-model="formTemp.isPickUp" placeholder="请选择">
                  <el-option
                    v-for="(value, key) in isPickUpMap"
                    :key="key"
                    :label="value"
                    :value="Number(key)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同号:" prop="contractNumber">
                <el-input v-model.trim="formTemp.contractNumber" :maxlength="30" @input="formTemp.contractNumber=formTemp.contractNumber.replace(/[^\d]/g, '')" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支付方式:" prop="defaultPaymentMethod">
                <el-select v-model="formTemp.defaultPaymentMethod" placeholder="请选择" @change="paymentMethodChange">
                  <el-option
                    v-for="item in paymentMethodMap"
                    :key="item.value"
                    :label="item.desc"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结款方式:" prop="settlementType">
                <el-select v-model="formTemp.settlementType" placeholder="请选择" disabled>
                  <el-option
                    v-for="item in settlementTypeMap"
                    :key="item.value"
                    :label="item.desc"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结款天数:" prop="intSpare2">
                <!-- <el-input-number v-model="temp.intSpare2" controls-position="right" :min="0" :precision="0" style="width: 100px;" /> -->
                <el-input-number v-model.trim="formTemp.intSpare2" size="mini" controls-position="right" :precision="0" :min="1" :max="10000" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="月结授信额度:" prop="decimalSpare1">
                <el-input v-model.trim="formTemp.decimalSpare1" :disabled="decimalDisabled" :maxlength="15" @input="formTemp.decimalSpare1=temp.decimalSpare1.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/,'$1')" @blur="formatInput($event)" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item title="证件信息(点击展开更多可填项)" name="7">
          <el-button v-if="formTemp.cardItems.length===0" type="primary" class="addCardBtn" @click="addCardItems">新增</el-button>
          <div style="width: 100%;">
            <div v-for="(item, index) in formTemp.cardItems" :key="index" class="csminfoBox">
              <el-row :gutter="16" class="row-box">
                <el-col :span="8">
                  <el-form-item label="证件类型:" prop="cardType">
                    <el-select v-model="item.cardType" placeholder="请选择">
                      <el-option
                        v-for="item2 in cardTypeAll"
                        :key="item2.value"
                        :label="item2.desc"
                        :value="item2.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="证件编号:" prop="cardNo">
                    <el-input v-model.trim="item.cardNo" :maxlength="20" placeholder="">
                      <el-button slot="append" class="append-search" @click.prevent="getCardNo(index)">获取</el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-button v-if="formTemp.cardItems.length>1" type="danger" @click="removeCardItems(index)">移除</el-button>
                  <el-button v-if="index===formTemp.cardItems.length-1" type="primary" @click="addCardItems">新增</el-button>
                </el-col>
              </el-row>
              <el-row :gutter="16" class="row-box">
                <el-col :span="24">
                  <el-form-item label="证件图片:">
                    <el-upload
                      action="#"
                      :data="item.qiniuData"
                      :before-upload="(file)=>beforeUpload(file, index)"
                      list-type="picture-card"
                      :file-list="item.fileList"
                      :limit="limit"
                      :on-exceed="handleExceed"
                      :http-request="(e)=>uploadToQiNiu(e, index)"
                      multiple
                      accept="image/jpeg, image/jpg, image/png"
                    >
                      <i slot="default" class="el-icon-plus" />
                      <div slot="file" slot-scope="{file}">
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                        <span class="el-upload-list__item-actions">
                          <span
                            class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview(file)"
                          >
                            <i class="el-icon-zoom-in" />
                          </span>
                          <span
                            v-if="!disabled"
                            class="el-upload-list__item-delete"
                            @click="handleRemove2(file, index)"
                          >
                            <i class="el-icon-delete" />
                          </span>
                        </span>
                      </div>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible" append-to-body>
                      <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-collapse-item>
        <el-collapse-item title="其他信息(点击展开更多可填项)" name="8">
          <el-row :gutter="16" class="row-box">
            <el-col :span="8">
              <el-form-item label="备用字段1:" prop="strSpare1">
                <el-input v-model.trim="formTemp.strSpare1" :maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备用字段2:" prop="strSpare2">
                <el-input v-model.trim="formTemp.strSpare2" :maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备用字段3:" prop="strSpare3">
                <el-input v-model.trim="formTemp.strSpare3" :maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <location ref="location" />
    <salesman ref="salesman" :tree-data="treeData" />
  </div>
</template>

<script>
  import { selectAreaCode, queryOrgCode, customerUpdate, customerAttachment, queryQiniuyunUploadToken } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { csmLevelMap, defaultPaymentMethodMap, csmFromPlatMap, isPickUpMap } from '@/utils/map'
  import * as qiniu from 'qiniu-js'
  import Location from './Location'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import Salesman from './Salesman'
  import { isSfzh } from '@/utils'
  import watermark from '@/utils/watermark'
  import compress from '@/utils/compress'

  export default {
    name: 'clientInformation',
    components: {
      Location, Salesman
    },
    props: {
      treeData: {
        type: Array,
        required: true
      },
      temp: {
        type: Object,
        required: true
      },
      allMap: {
        type: Object,
        required: true
      }
    },
    // watch: {
    //   formTemp: {
    //     handler(formTemp) {
    //       this.temp = {...formTemp}
    //     },
    //     deep: true
    //   }
    // },
    data() {
      const validateSfzh = (rule, value, callback) => {
        const sp1 = this.corpSettingData.sp1
        // 启用实名制开户
        if ((sp1 >> 30) & 0x01 > 0) {
          if (value === '') {
            callback(new Error('请输入身份证号'))
          }
          callback()
        } else {
          if (value !== '') {
            if (!isSfzh(value)) {
              callback(new Error('身份证号格式不正确'))
            }
            callback()
          }
          callback()
        }
      }
      return {
        activeNames: ['1', '2', '3', '4', '5'],
        activeTabName: 'customer',
        formTemp: {
          area: [],
          csmName: '',
          csmCode: '',
          csmType: 1,
          csmRgPhone: '',
          subType: '',
          contact: '',
          orgSNNo: '',
          csmFloor: 1,
          unCheckQuality: '',
          sfzh: '',
          sfzName: '',
          sfzAddress: '',
          cardType: '',
          cardNo: '',
          newType: 2,
          defaultPaymentMethod: 1,
          newFrom: 8,
          salesmanName: '',
          isPickUp: 0,
          settlementType: 1,
          createTime: moment(),
          contractNumber: '',
          decimalSpare1: '',
          intSpare2: '',
          remark: '',
          strSpare1: '',
          strSpare2: '',
          strSpare3: '',
          strSpare4: '',
          csmRgAddress: '', // 地址
          addressItems: [],
          phoneItems: [],
          cardItems: []
        },
        baseUrl: 'http://image.haoyunqi.com.cn/',
        csmTypeList: [],
        subTypeList: [
          {
            label: '餐饮',
            value: 1
          },
          {
            label: '餐饮(个人)',
            value: 2
          },
          {
            label: '工厂',
            value: 3
          },
          {
            label: '机关事业单位',
            value: 4
          },
          {
            label: '部队',
            value: 5
          },
          {
            label: '居民(个人)',
            value: 6
          },
          {
            label: '学校',
            value: 7
          },
          {
            label: '其他商业',
            value: 8
          },
          {
            label: '餐饮(连锁)',
            value: 9
          },
          {
            label: '住宿业',
            value: 10
          },
          {
            label: '商贸服务业',
            value: 11
          },
          {
            label: '医疗卫生',
            value: 12
          },
          {
            label: '社会保障',
            value: 13
          }
        ],

        decimalDisabled: true,
        cuindex: '',
        cascaderKey: 0,
        cardTypeAll: [],
        cardTypeAllList: [],
        ck: 0,
        csmCode: '',
        csmId: 0,
        customerLerel: 0,
        optFlag: undefined,
        cardInfo_temp: null, // 临时保存过滤的证件列表中身份证类型数据
        customerFromPlatMap: [],
        customerQualityMap: [],
        csmTypeMap: [],
        newTypeMap: [],
        paymentMethodMap: [],
        settlementTypeMap: [],
        csmLevelMap,
        defaultPaymentMethodMap,
        csmFromPlatMap,
        isPickUpMap,
        visible: false,
        currentOrg: null,
        currentSalesman: null,
        point: null,
        rules: {
          csmType: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
          csmCode: [{ required: true, message: '请输入户号', trigger: 'change' }],
          csmName: [{ required: true, message: '请输入客户名称', trigger: 'change' }],
          sfzName: [{ required: true, message: '请输入身份证姓名', trigger: 'change' }],
          sfzh: [{ validator: validateSfzh, trigger: 'blur' }],
          sfzAddress: [{ required: true, message: '请输入身份证地址', trigger: 'change' }],
          zzbh: [{ required: true, message: '请输入证件号码', trigger: 'change' }],
          contact: [{ required: true, message: '请输入联系人', trigger: 'change' }],
          csmPhone: [{ required: true, message: '请输入联系人电话', trigger: 'change' }],
          addressProps: [{ required: true, message: '请选择省市区', trigger: 'change' }],
          csmAddress: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
          doorplate: [{ required: true, message: '请输入门牌号', trigger: 'change' }],
          orgSNNo: [{ required: true, message: '请选择所属机构', trigger: 'change' }]
        },
        addressProps: {
          lazy: true,
          checkStrictly: true,
          lazyLoad(node, resolve) {
            const { level, value } = node
            mergeAsyncFunc(selectAreaCode, { areaCode: value || 0 })
              .then((res) => {
                const nodes = res.data.map(item => ({
                  value: item.areaCode,
                  label: item.areaName,
                  leaf: level >= 3
                }))
                resolve(nodes)
              })
              .catch(() => {
                node.loading = false
                node.loaded = false
              })
          }
        },
        addIcon: require('../../../../assets/add.png'),
        removeIcon: require('../../../../assets/remove.png'),
        box: [],
        newBox: [],
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        fileList: [],
        limit: 3
      }
    },
    computed: {
      ...mapGetters([
        'corpSettingData'
      ]),
      ...mapGetters([
        'userInfo'
      ])
    },
    async mounted() {
      this.formTemp = { ...this.temp }
      await this.getDefaultData()
    },
    methods: {
      echoData() {
        this.formTemp = { ...this.temp }
        this.getDefaultData()
      },
      async open(query) {
        await this.init()
      },
      init() {
        if (this.customerQualityMap['1'] && this.customerQualityMap['1'] === '普通') {
          this.formTemp.unCheckQuality = 1
        }
      },
      changeCsmType(csmType) {
        this.formTemp.subType = ''
        if (csmType === 1) {
          this.subTypeList = this.subTypeList1
        } else {
          this.subTypeList = this.subTypeList2
        }
      },
      paymentMethodChange(defaultPaymentMethod) {
        if (defaultPaymentMethod === 16) {
          this.formTemp.settlementType = 2
          this.decimalDisabled = false
        } else {
          this.formTemp.settlementType = 1
          this.decimalDisabled = true
        }
      },
      contactChange(contact) {

      },
      csmPhoneChange(csmPhone) {

      },
      // 选择级联框
      selectCascader(val) {
        console.log(val)
      },
      async getDefaultData(CsmDefaultData) {
        await this.getQiniuyunUploadToken()
        this.cardTypeAll = JSON.parse(this.allMap.cardType)
        this.cardTypeAllList = JSON.parse(this.allMap.cardTypeAllList)
        this.ck = Number(this.allMap.ck)
        this.csmCode = this.allMap.csmCode
        // this.csmLerel = Number(this.allMap.csmLerel)
        this.csmTypeMap = JSON.parse(this.allMap.customerType)
        this.customerFromPlatMap = JSON.parse(this.allMap.customerFromPlat)
        this.customerQualityMap = JSON.parse(this.allMap.customerQuality)
        this.newTypeMap = JSON.parse(this.allMap.newType)
        this.paymentMethodMap = JSON.parse(this.allMap.paymentMethod)
        this.settlementTypeMap = JSON.parse(this.allMap.settlementType)
        if (!this.formTemp.unCheckQuality) this.formTemp.unCheckQuality = '' // 解开后会造成没有客户等级默认显示0
        if (!this.formTemp.defaultPaymentMethod) this.formTemp.defaultPaymentMethod = null // 解开后会造成没有客户支付方式默认显示0
        // 详细地址
        const mainAddress = this.formTemp.addressItems.find(l => l.isMain)
        if (mainAddress) {
          this.formTemp.csmFloor = mainAddress.csmFloor
        } else {
          this.formTemp.csmFloor = 1
        }
        if (this.formTemp.addressItems) {
          this.formTemp.addressItems.forEach((item, index) => {
            item.rowId = Symbol('rowId')
            console.log(item)
            item.area = []
            if (item.provinceCode) {
              item.area.push(item.provinceCode)
            }
            if (item.cityCode) {
              item.area.push(item.cityCode)
            }
            if (item.countryCode) {
              item.area.push(item.countryCode)
            }
            if (item.streetCode) {
              item.area.push(item.streetCode)
            }
          })
        }
        if (this.formTemp.cardItems) {
          const qiniuData = { // 这里是直接绑定data的值
            key: '', // 图片名字处理
            token: this.token, // 七牛云token
            data: {},
            bucket: ' '
          }
          this.formTemp.cardItems.forEach((item, index) => {
            this.$set(this.formTemp.cardItems[index], 'fileList', [])
            this.$set(this.formTemp.cardItems[index], 'qiniuData', qiniuData)
          })
        }
        this.temp.deleteFileList = []
        this.getData()
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken() {
        const res = await queryQiniuyunUploadToken()
        this.token = res.data
      },
      async getData() {
        const res = await customerAttachment({ csmCode: this.temp.csmCode })
        this.cardList = res.data.cardItems
        this.formTemp.cardItems.forEach((item, index) => {
          this.cardList.forEach((item2) => {
            if (item.cardNo === item2.cardNo) {
              if (item2.picInfos) {
                item2.picInfos = item2.picInfos.map(item => {
                  return {
                    name: item.sourceName,
                    uid: item.id,
                    upload: true,
                    url: item.url ? this.baseUrl + item.url : ''
                  }
                })
                item2.picInfos.forEach((item3) => {
                  this.formTemp.cardItems[index].fileList.push(item3)
                })
              }
            }
          })
        })
      },
      // 获取客户编号
      async getCsmCode() {
        const res = await queryOrgCode({
          codeType: 2
        })
        this.formTemp.csmCode = res.data
      },
      // 获取证件编号
      async getCardNo(index) {
        const res = await queryOrgCode({
          codeType: 18
        })
        this.formTemp.cardItems[index].cardNo = res.data
      },
      // 点击获取销售员
      async openSalesman() {
        const res = await this.$refs.salesman.open()
        this.currentSalesman = res
        this.$set(this.formTemp, 'salesmanName', res.userName)
      },
      // 清除销售员
      clearSalesman() {
        this.$set(this.formTemp, 'salesmanName', '')
        this.currentSalesman = null
      },
      csmNameChange(value) {
        // this.formTemp.contact = value
      },
      visibleChange(visible) {
        if (!visible) {
          console.log('blur')
          this.formTemp.addressItems.forEach((item, index) => {
            const name = 'cascader' + index
            const address = this.$refs[name][0].getCheckedNodes()[0]
            if (address) {
              const pathNodes = address.pathNodes
              if (pathNodes.length < 4) {
                this.$message.warning('请选择省市区街道')
                this.$refs[name][0].$refs.panel.clearCheckedNodes()
                this.formTemp.addressItems[index].area = []
                this.formTemp.addressItems[index].provinceName = ''
                this.formTemp.addressItems[index].provinceCode = ''
                this.formTemp.addressItems[index].cityName = ''
                this.formTemp.addressItems[index].cityCode = ''
                this.formTemp.addressItems[index].countryName = ''
                this.formTemp.addressItems[index].countryCode = ''
                this.formTemp.addressItems[index].streetName = ''
                this.formTemp.addressItems[index].streetCode = ''
              }
            }
          })
        }
      },
      success(type) {
        this.$refs.dataForm.validate(async valid => {
          if (!valid) return
          const csmTypeInfo = this.formTemp.csmType
          const sp5 = this.corpSettingData.sp5
          if (sp5 >> 13 & 0x01) {
            if (!this.formTemp.csmCode) {
              if (csmTypeInfo === 2 || csmTypeInfo === 4) {
                if (!this.formTemp.cardNo) {
                  this.$message('证件不能为空')
                  return
                } else {
                  if (this.formTemp.cardType !== 4) {
                    this.$message.warning('证件类型必须为营业执照')
                    return
                  }
                }
              }
            }
          }
          const customerInfo = {
            csmId: this.formTemp.csmId,
            csmCode: this.formTemp.csmCode,
            csmName: this.formTemp.csmName,
            sfzh: this.formTemp.sfzh,
            sfzName: this.formTemp.sfzName,
            sfzAddress: this.formTemp.sfzAddress,
            csmRgPhone: this.formTemp.csmRgPhone,
            contact: this.formTemp.contact,
            csmRgAddress: this.formTemp.csmRgAddress,
            nearStation: this.currentOrg.orgId,
            nearStationName: this.currentOrg.orgName,
            orgSNNo: this.currentOrg.orgSNNo,
            cardType: this.formTemp.cardType,
            cardNo: this.formTemp.cardNo,
            newType: this.formTemp.newType,
            defaultPaymentMethod: this.formTemp.defaultPaymentMethod,
            csmType: this.formTemp.csmType,
            newFrom: this.formTemp.newFrom,
            salesman: this.formTemp.salesman || 0,
            remark: this.formTemp.remark,
            createTime: moment(this.formTemp.createTime).format(),
            settlementType: this.formTemp.settlementType,
            contractNumber: this.formTemp.contractNumber,
            strSpare1: this.formTemp.strSpare1,
            strSpare2: this.formTemp.strSpare2,
            strSpare3: this.formTemp.strSpare3,
            strSpare4: this.formTemp.strSpare4,
            phoneItems: this.temp.phoneItems,
            addressItems: this.temp.addressItems,
            cardItems: this.temp.cardItems
          }
          customerInfo.addressItems.forEach((item, index) => {
            const name = 'cascader' + index
            const address = this.$refs[name][0].getCheckedNodes()[0]
            if (address) {
              const pathNodes = address.pathNodes
              switch (pathNodes.length) {
              case 1:
                item.provinceName = pathNodes[0].label
                item.provinceCode = pathNodes[0].value
                break
              case 2:
                item.provinceName = pathNodes[0].label
                item.provinceCode = pathNodes[0].value
                item.cityName = pathNodes[1].label
                item.cityCode = pathNodes[1].value
                break
              case 3:
                item.provinceName = pathNodes[0].label
                item.provinceCode = pathNodes[0].value
                item.cityName = pathNodes[1].label
                item.cityCode = pathNodes[1].value
                item.countryName = pathNodes[2].label
                item.countryCode = pathNodes[2].value
                break
              case 4:
                item.provinceName = pathNodes[0].label
                item.provinceCode = pathNodes[0].value
                item.cityName = pathNodes[1].label
                item.cityCode = pathNodes[1].value
                item.countryName = pathNodes[2].label
                item.countryCode = pathNodes[2].value
                item.streetName = pathNodes[3].label
                item.streetCode = pathNodes[3].value
                break
              }
            } else {
              item.provinceName = ''
              item.provinceCode = ''
              item.cityName = ''
              item.cityCode = ''
              item.countryName = ''
              item.countryCode = ''
              item.streetName = ''
              item.streetCode = ''
            }
            item.orgId = item.currentOrg.orgId
            item.orgName = item.currentOrg.orgName
            item.orgSNNo = item.currentOrg.orgSNNo
            const f = item.csmFloor // 楼层
            const maxF = this.corpSettingData.sp1 >> 18 & 0xF
            if (maxF > 0) {
              if (f > maxF) {
                this.$message('楼层不能超过' + maxF + '层')
                return
              }
            }
            // 经度纬度
            if (item.point) {
              item.lat = this.temp.addressItems[index].point.lat
              item.lng = this.temp.addressItems[index].point.lng
            }
          })
          // 客户等级
          if (this.customerLerel === 1) { // 没有用字典
            customerInfo.csmQuality = this.formTemp.unCheckQuality
          } else {
            customerInfo.unCheckQuality = this.formTemp.unCheckQuality
          }
          if (this.currentSalesman) {
            customerInfo.salesmanName = this.currentSalesman.salesmanName
          }
          if (type === 2 || (type === 0 && this.ck !== 0)) {
            customerInfo.csmStatus = 2
          }
          if (!this.formTemp.csmId && (this.corpSettingData.sp1 >> 5 & 0x01) === 0x01) {
            customerInfo.csmStatus = 1
          }
          if (this.formTemp.isPickUp === 0 && this.formTemp.csmId > 0) {
            customerInfo.isPickUp = -1
          }
          const f = this.formTemp.csmFloor // 楼层
          const maxF = this.corpSettingData.sp1 >> 18 & 0xF
          if (maxF > 0) {
            if (f > maxF) {
              this.$message('楼层不能超过' + maxF + '层')
              return
            }
          }
          // 经度纬度
          if (this.point) {
            customerInfo.lat = this.point.lat
            customerInfo.lng = this.point.lng
          }
          customerInfo.phoneItems = [{
            csmPhone: customerInfo.csmRgPhone,
            contact: customerInfo.contact,
            isMain: 1
          }]
          customerInfo.addressItems = [{
            csmAddress: customerInfo.csmRgAddress,
            provinceCode: customerInfo.provinceCode,
            provinceName: customerInfo.provinceName,
            cityCode: customerInfo.cityCode,
            cityName: customerInfo.cityName,
            countryCode: customerInfo.countryCode,
            countryName: customerInfo.countryName,
            streetCode: customerInfo.streetCode,
            streetName: customerInfo.streetName,
            orgId: customerInfo.nearStation,
            orgName: customerInfo.nearStationName,
            orgSNNo: customerInfo.orgSNNo,
            isMain: 1,
            csmFloor: this.formTemp.csmFloor || 1,
            longitude: customerInfo.lon,
            latitude: customerInfo.lat
          }]
          const decimalSpare1 = this.formTemp.decimalSpare1
          if (decimalSpare1 !== '') {
            customerInfo.decimalSpare1 = decimalSpare1
          }
          const intSpare2 = this.formTemp.intSpare2
          if (intSpare2 !== '') {
            customerInfo.intSpare2 = intSpare2
          }
          this.edit(customerInfo)
        })
      },
      async edit(params) {
        await customerUpdate(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      // 定位
      async location(index) {
        const res = await this.$refs.location.open()
        // 处理详细地址
        this.temp.csmAddress = res.address
        this.temp.addressItems[index].csmAddress = res.address
        this.temp.addressItems[index].point = res.point
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
      },
      reset() {
        this.formTemp = {
          phoneItems: [],
          addressItems: [],
          cardItems: [],
          area: [],
          csmName: '',
          csmCode: '',
          csmType: 1,
          csmRgPhone: '',
          contact: '',
          orgName: '',
          csmFloor: 1,
          unCheckQuality: '',
          sfzh: '',
          sfzName: '',
          sfzAddress: '',
          cardType: '',
          cardNo: '',
          newType: 2,
          defaultPaymentMethod: 1,
          newFrom: 8,
          salesmanName: '',
          isPickUp: 0,
          settlementType: 1,
          createTime: '',
          contractNumber: '',
          decimalSpare1: '',
          intSpare2: '',
          strSpare1: '',
          strSpare2: '',
          strSpare3: '',
          strSpare4: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      // 添加联系人
      addLinkMan() {
        this.formTemp.phoneItems.push({ contact: '', csmPhone: '', isMain: false })
      },
      // 移除联系人
      removeLinkMan(index) {
        this.formTemp.phoneItems.splice(index, 1)
      },
      // 添加地址
      addCsminfo() {
        const rowId = Symbol('rowId')
        this.formTemp.addressItems.push({ contact: '', csmPhone: '', area: '', csmAddress: '', csmFloor: '', showInput: false, rowId: rowId })
        // this.formTemp.phoneItems.push({ contact: '', csmPhone: '', rowId: rowId })
        this.formTemp.phoneItems.push(this.formTemp.addressItems[this.formTemp.addressItems.length - 1])
        this.formTemp.phoneItems[this.formTemp.phoneItems.length - 1].disabled = true
      },
      // 移除地址
      removeCsminfo(index) {
        const rowId = this.formTemp.addressItems[index].rowId
        this.formTemp.addressItems.splice(index, 1)
        this.formTemp.phoneItems.forEach((item, index) => {
          if (item.rowId === rowId) {
            this.formTemp.phoneItems.splice(index, 1)
          }
        })
      },
      crmPhoneChange(value, rowId, index) {
        let hasRow = false
        let hasItem = false
        this.formTemp.phoneItems.forEach((item, index) => {
          if (item.rowId !== rowId) {
            if (item.csmPhone === value) {
              // this.$message.warning('该联系电话已存在')
              this.formTemp.phoneItems.splice(index, 1)
              hasItem = true
            }
          }
          if (item.rowId === rowId) {
            hasRow = true
          }
        })
        if (!hasRow) {
          if (!hasItem) {
            this.formTemp.phoneItems.push(this.formTemp.addressItems[index])
            this.formTemp.phoneItems[this.formTemp.phoneItems.length - 1].disabled = true
          }
        }
      },
      phoneChange(value, index) {
        this.formTemp.phoneItems.forEach((item, index2) => {
          if (index2 < this.formTemp.phoneItems.length - 1) {
            if (item.csmPhone === value) {
              this.$alert('该联系电话已存在，请删除', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.formTemp.phoneItems.splice(index, 1)
                }
              })
            }
          }
        })
      },
      // 新增证件
      addCardItems() {
        const qiniuData = { // 这里是直接绑定data的值
          key: '', // 图片名字处理
          token: this.token, // 七牛云token
          data: {},
          bucket: ' '
        }
        this.formTemp.cardItems.push({ cardType: '', cardNo: '', fileList: [], qiniuData: qiniuData })
      },
      // 移除证件
      removeCardItems(index) {
        this.formTemp.cardItems.splice(index, 1)
      },
      isMainChange(value, csmPhone, index) {
        if (value) {
          this.formTemp.addressItems.forEach((item, index2) => {
            if (index !== index2) {
              this.$set(this.formTemp.addressItems[index2], 'isMain', false)
            }
            this.formTemp.phoneItems.forEach((item, index3) => {
              if (item.csmPhone !== csmPhone) {
                this.$set(this.formTemp.phoneItems[index3], 'isMain', false)
              }
              if (item.csmPhone === csmPhone && csmPhone) {
                this.$set(this.formTemp.phoneItems[index3], 'isMain', true)
              }
            })
          })
        }
      },
      // 营业执照信息
      uploadChange(file) {
        this.fileList.push(file)
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handleRemove(file) {
        this.fileList.forEach((item, index) => {
          if (item.uid === file.uid) {
            this.fileList.splice(index, 1)
          }
        })
      },
      // 证件信息
      uploadChange2(file, index) {
        this.temp.cardItems[index].fileList.push(file)
      },
      beforeUpload(file, index) {
        const key = `${this.userInfo.corpCode}_${new Date().getTime()}_${file.name}`
        this.formTemp.cardItems[index].qiniuData.key = key
        return this.formTemp.cardItems[index].qiniuData
      },
      uploadToQiNiu(e, index) {
        const _this = this
        const file = e.file // Blob 对象，上传的文件
        const config = {
          useCdnDomain: true, // 表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
          region: qiniu.region.z0 // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域
        }
        const putExtra = {
          fname: this.formTemp.cardItems[index].qiniuData.key, // 文件原文件名
          params: {}, // 用来放置自定义变量
          mimeType: ['image/png', 'image/jpeg', 'image/jpg'] // 用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
        }
        this.changeFile(file, function(file) {
          console.log(file)
          var observable = qiniu.upload(file, _this.formTemp.cardItems[index].qiniuData.key, _this.formTemp.cardItems[index].qiniuData.token, putExtra, config)
          observable.subscribe({
            next: result => {
              // 主要用来展示进度
              // console.log(result)
            },
            error: errResult => {
              // 失败报错信息
              // console.log(errResult)
              _this.$message.error('上传失败')
            },
            complete: result => {
              // 接收成功后返回的信息
              _this.formTemp.cardItems[index].fileList.push(result)
              _this.formTemp.cardItems[index].fileList[_this.formTemp.cardItems[index].fileList.length - 1].url = _this.baseUrl + result.key
            }
          })
        }, function() {
          _this.$message.error('压缩失败')
        })
      },
      changeFile(file, onload, onerror) {
        compress(file, 3 * 1024 * 1024, 2 * 1024 * 1024, function(_file) {
          watermark(_file, '仅供附件上传使用，他用无效', onload, onerror)
        }, onerror)
      },
      handleRemove2(file, index) {
        this.formTemp.cardItems[index].fileList.forEach((item, index2) => {
          if (item.uid === file.uid) {
            if (item.upload) {
              this.temp.deleteFileList.push({
                cardType: this.formTemp.cardItems[index].cardType,
                cardNo: this.formTemp.cardItems[index].cardNo,
                picId: item.uid
              })
            }
            this.formTemp.cardItems[index].fileList.splice(index2, 1)
          }
        })
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前用户证件附件可继续上传最大张数：${this.limit}张，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      }
    }
  }
</script>

<style lang='scss' scoped>
.addCsmDialog {
  /deep/ .el-dialog {
    height: 100vh;
    margin-top: 0 !important;
  }
  /deep/.el-dialog .el-dialog__body {
    max-height: 86vh !important;
    padding: 10px 40px;
    overflow: auto;
  }
  /deep/.el-dialog .el-dialog__footer {
    padding: 10px !important;
  }
  /deep/ .el-collapse-item__header {
    height: 38px;
    padding-left: 10px;
    font-size: 14px;
    line-height: 38px;
    color: #38BDBD;
    border-left: 5px solid #38BDBD;
  }
  /deep/.el-dialog .el-collapse-item__content {
    // padding: 5px 0;
    padding: 0;
  }
}
.form {
  display: flex;
  flex-wrap: wrap;
  .collapse {
    width: 100%;
  }
  & /deep/ .el-form-item {
    width: 100%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  & /deep/ .form-row-item {
    width: 100%;
    .el-form-item__content > .el-input {
      width: 30%;
    }
    .el-form-item__content > .el-select {
      width: 30%;
    }
  }
  .row-box {
    padding: 5px 25px 0 0;
  }
  .csminfoBox {
    position: relative;
    width: 100%;
    padding: 10px 0 0 0;
    margin-top: 10px;
    background-color: #FAFAFA;
  }
  .icon-box {
    position: absolute;
    top: 40%;
    right: 40px;
    display: none;
  }
  .tel-box {
    width: 100%;
  }
  .bottomBtn {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
    .btn {
      margin-right: 10px;
      color: #38BDBD;
      cursor: pointer;
    }
    .danger {
      color: #F56C6C;
    }
  }
  .addCardBtn {
    margin: 10px;
  }
}
</style>
